package com.example.module_hp_white_noise.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import com.example.module_hp_white_noise.R;
import com.example.module_hp_white_noise.base.BaseUtils;
import com.example.module_hp_white_noise.entity.Music;
import com.example.module_hp_white_noise.service.MusicService;
import com.example.module_hp_white_noise.util.Utils;
import com.example.module_hp_white_noise.view.RotateAnimator;
import com.fwlst.lib_base.utils.AdUtils;

import java.util.List;
import java.util.Objects;

public class HpWhiteNoiseChildPlayActivity extends AppCompatActivity implements View.OnClickListener{
    private Context mContext;
    private TextView musicTitleView;
    private TextView musicArtistView;
    private ImageView musicImgView;
    private ImageView btnPlayMode;
    private ImageView btnPlayPre;
    private ImageView btnPlayOrPause;
    private ImageView btnPlayModeOnce;
    private ImageView btnPlayModeCycle;
    private ImageView btnPlayNext;
    private ImageView btnPlayingList;
    private TextView nowTimeView;
    private TextView totalTimeView;
    private SeekBar seekBar;
    private RotateAnimator rotateAnimator;
    private MusicService.MusicServiceBinder serviceBinder;
    private Music music;
    private int thisImgUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hp_white_noise_child_play);
        BaseUtils.setStatusBar(this,0xFF1E2746);
        mContext = this;
        //banner广告
        AdUtils.INSTANCE.loadBannerAd(this,findViewById(R.id.bannerContainer));
        //接收传值
        try {
            Bundle bd=this.getIntent().getExtras();
            String songUrl = bd.getString("songUrl");
            String imgUrl = bd.getString("imgUrl");
            String title = bd.getString("title");
            Log.e("资源ID",imgUrl);
            if(songUrl!=null){
                music = new Music(
                        Utils.HTTPS_URL+songUrl,
                        title,
                        "",
                        imgUrl,
                        true
                );
            }
        }catch (Exception e){
        }
        TextView artist = findViewById(R.id.artist);
        List<Integer> sum = BaseUtils.genUniqueRandomVal(100,1000,1);
        Float sumVal = Float.valueOf((float) (sum.get(0)*0.01));
        artist.setText(sumVal+"万人听过");
        //初始化
        initActivity();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
        AdUtils.INSTANCE.destroyBannerAd();
    }

    // 控件监听
    @Override
    public void onClick(View v) {
        if(!BaseUtils.isNetworkConnected(mContext)){
            Toast.makeText(mContext, "网络连接异常", Toast.LENGTH_SHORT).show();
            return;
        }
        int id = v.getId();
        if (id == R.id.play_mode_once) {// 改变播放模式
            int mode = serviceBinder.getPlayMode();
            if(mode == Utils.TYPE_SINGLE){
                serviceBinder.setPlayMode(Utils.TYPE_ONCE);
                btnPlayModeCycle.setImageResource(R.drawable.ic_danqu_2);
                btnPlayModeOnce.setImageResource(R.drawable.ic_danqu_01);
            }
            /*switch (mode) {
                case Utils.TYPE_ORDER:
                    serviceBinder.setPlayMode(Utils.TYPE_SINGLE);
                    //Toast.makeText(PlayerActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();
                    btnPlayMode.setImageResource(R.drawable.ic_singlerecycler);
                    break;
                case Utils.TYPE_SINGLE:
                    serviceBinder.setPlayMode(Utils.TYPE_RANDOM);
                    //Toast.makeText(PlayerActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                    btnPlayMode.setImageResource(R.drawable.ic_random);
                    break;
                case Utils.TYPE_RANDOM:
                    serviceBinder.setPlayMode(Utils.TYPE_ORDER);
                    //Toast.makeText(PlayerActivity.this, "列表循环", Toast.LENGTH_SHORT).show();
                    btnPlayMode.setImageResource(R.drawable.ic_playrecycler);
                    break;
                default:
            }*/
        }else if(id == R.id.play_mode_cycle){
            int mode = serviceBinder.getPlayMode();
            if(mode == Utils.TYPE_ONCE){
                serviceBinder.setPlayMode(Utils.TYPE_SINGLE);
                btnPlayModeCycle.setImageResource(R.drawable.ic_danqu_02);
                btnPlayModeOnce.setImageResource(R.drawable.ic_danqu_1);
            }
        }else if (id == R.id.play_or_pause) {// 播放或暂停
            serviceBinder.playOrPause();
        }/*else if (id == R.id.play_pre) {// 上一首
            serviceBinder.playPre();
        } else if (id == R.id.play_next) {// 下一首
            serviceBinder.playNext();
        } else if (id == R.id.playing_list) {// 播放列表
            showPlayList();
        }*/
    }

    private void initActivity() {
        musicTitleView = findViewById(R.id.title);
        //musicArtistView = findViewById(R.id.artist);
        musicImgView = findViewById(R.id.imageView);
        btnPlayModeOnce = findViewById(R.id.play_mode_once);
        btnPlayModeCycle = findViewById(R.id.play_mode_cycle);
        btnPlayOrPause = findViewById(R.id.play_or_pause);
        /*btnPlayPre = findViewById(R.id.play_pre);
        btnPlayNext = findViewById(R.id.play_next);
        btnPlayingList = findViewById(R.id.playing_list);*/
        seekBar = findViewById(R.id.seekbar);
        nowTimeView = findViewById(R.id.current_time);
        totalTimeView = findViewById(R.id.total_time);
        ImageView needleView = findViewById(R.id.ivNeedle);

        // ToolBar
        Toolbar toolbar = findViewById(R.id.back_tb);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        setSupportActionBar(toolbar);

        // 设置监听
        btnPlayModeOnce.setOnClickListener(this);
        btnPlayModeCycle.setOnClickListener(this);
        btnPlayOrPause.setOnClickListener(this);
        //btnPlayPre.setOnClickListener(this);
        //btnPlayNext.setOnClickListener(this);
        //btnPlayingList.setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //拖动进度条时
                if(!BaseUtils.isNetworkConnected(mContext)){
                    //Toast.makeText(mContext, "网络连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                nowTimeView.setText(Utils.formatTime((long) progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(!BaseUtils.isNetworkConnected(mContext)){
                    Toast.makeText(mContext, "网络连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                serviceBinder.seekTo(seekBar.getProgress());
            }
        });

        //初始化动画
        rotateAnimator = new RotateAnimator(this, musicImgView, needleView);
        rotateAnimator.set_Needle();
        // 绑定service
        Intent i = new Intent(this, MusicService.class);
        bindService(i, mServiceConnection, BIND_AUTO_CREATE);
        //this.getApplicationContext().bindService(i, mServiceConnection, BIND_AUTO_CREATE);
    }
    private void initMusic(){
        serviceBinder.addPlayList(music);
        serviceBinder.setPlayMode(Utils.TYPE_ONCE);
        btnPlayModeCycle.setImageResource(R.drawable.ic_danqu_2);
        btnPlayModeOnce.setImageResource(R.drawable.ic_danqu_01);
    }
    //定义与服务的连接的匿名类
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功后，取得MusicSercice提供的接口
            serviceBinder = (MusicService.MusicServiceBinder) service;
            if(music!=null){
                if(!BaseUtils.isNetworkConnected(mContext)){
                    Toast.makeText(mContext, "网络连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                initMusic();
            }
            //注册监听器
            serviceBinder.registerOnStateChangeListener(listenr);

            //获得当前音乐
            Music item = serviceBinder.getCurrentMusic();
            thisImgUrl = getApplicationContext().getResources().getIdentifier(item.imgUrl,"drawable",getApplicationContext().getPackageName());
            if(item == null) {
                //当前音乐为空, seekbar不可拖动
                seekBar.setEnabled(false);
            }
            else if (serviceBinder.isPlaying()){
                //如果正在播放音乐, 更新信息
                musicTitleView.setText(item.title);
                //musicArtistView.setText(item.artist);
                btnPlayOrPause.setImageResource(R.drawable.hp_ic_pause);
                rotateAnimator.playAnimator();

                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(thisImgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(musicImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    //Bitmap img = Utils.getLocalMusicBmp(resolver, thisImgUrl);
                    Glide.with(getApplicationContext())
                            .load(thisImgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(musicImgView);
                }
            }
            else {
                //当前有可播放音乐但没有播放
                musicTitleView.setText(item.title);
                //musicArtistView.setText(item.artist);
                btnPlayOrPause.setImageResource(R.drawable.hp_ic_play);
                if (item.isOnlineMusic){
                    Glide.with(getApplicationContext())
                            .load(thisImgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(musicImgView);
                }
                else {
                    ContentResolver resolver = getContentResolver();
                    //Bitmap img = Utils.getLocalMusicBmp(resolver, thisImgUrl);
                    Glide.with(getApplicationContext())
                            .load(thisImgUrl)
                            .placeholder(R.drawable.defult_music_img)
                            .error(R.drawable.defult_music_img)
                            .into(musicImgView);
                }
            }

            // 获取当前播放模式
            int mode = (serviceBinder.getPlayMode());
            switch (mode){
                case Utils.TYPE_ONCE:
                    btnPlayModeCycle.setImageResource(R.drawable.ic_danqu_2);
                    btnPlayModeOnce.setImageResource(R.drawable.ic_danqu_01);
                    break;
                case Utils.TYPE_ORDER:
                    //btnPlayMode.setImageResource(R.drawable.ic_playrecycler);
                    break;
                case Utils.TYPE_SINGLE:
                    btnPlayModeCycle.setImageResource(R.drawable.ic_danqu_02);
                    btnPlayModeOnce.setImageResource(R.drawable.ic_danqu_1);
                    //btnPlayMode.setImageResource(R.drawable.ic_singlerecycler);
                    break;
                case Utils.TYPE_RANDOM:
                    //btnPlayMode.setImageResource(R.drawable.ic_random);
                    break;
                default:
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //断开连接之后, 注销监听器
            serviceBinder.unregisterOnStateChangeListener(listenr);
        }
    };

    //实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {

        @Override
        public void onPlayProgressChange(long played, long duration) {
            seekBar.setMax((int) duration);
            totalTimeView.setText(Utils.formatTime(duration));
            nowTimeView.setText(Utils.formatTime(played));
            seekBar.setProgress((int) played);
        }

        @Override
        public void onPlay(final Music item) {
            //变为播放状态时
            musicTitleView.setText(item.title);
            //musicArtistView.setText(item.artist);
            btnPlayOrPause.setImageResource(R.drawable.hp_ic_pause);
            rotateAnimator.playAnimator();
            if (item.isOnlineMusic){
                Glide.with(getApplicationContext())
                        .load(thisImgUrl)
                        .placeholder(R.drawable.defult_music_img)
                        .error(R.drawable.defult_music_img)
                        .into(musicImgView);
            }
            else {
                ContentResolver resolver = getContentResolver();
                //Bitmap img = Utils.getLocalMusicBmp(resolver, thisImgUrl);
                Glide.with(getApplicationContext())
                        .load(thisImgUrl)
                        .placeholder(R.drawable.defult_music_img)
                        .error(R.drawable.defult_music_img)
                        .into(musicImgView);
            }
        }

        @Override
        public void onPause() {
            //变为暂停状态时
            btnPlayOrPause.setImageResource(R.drawable.hp_ic_play);
            rotateAnimator.pauseAnimator();
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void finish() {
        super.finish();
        //界面退出时的动画
        //overridePendingTransition(R.anim.bottom_silent,R.anim.bottom_out);
    }
}
